import {specialDetailCtrl} from './dailyCheck.trackHistoryDailog.controller.js';

function dailyCheckCtrl($rootScope, $scope, $http, ngDialog, ngDialogProblem) {
  'ngInject';

  let createUserName = $state.params.createUserName;

  let checkCompletedTimeFrom = $state.params.checkCompletedTimeFrom; // 巡查开始时间
  let checkCompletedTimeTo = $state.params.checkCompletedTimeTo; // 巡查结束时间

  let startDateFrom = $state.params.startDateFrom; // 当天巡查时间
  let startDateTo = $state.params.startDateTo; // 当天巡查时间

  this.queryData = {
    queryType: 0, // pc:0,app:1
    createUserName: createUserName,
    checkCompletedTimeFrom: checkCompletedTimeFrom,
    checkCompletedTimeTo: checkCompletedTimeTo,
    startDateFrom: startDateFrom,
    startDateTo: startDateTo,
  };

  this.dailyCheckList = {};

  // 不显示内容详细列表
  this.showDetailList = false;

  // 分页
  this.paginationData = {
    pageNum: 0,
    pageSize: 5,
    total: '',
  }

  // 页码变化时调用方法
  $scope.pageChange = () => {

    this.paginationData1 = {
      pageNum: this.paginationData.pageNum-1,
      pageSize: 5,
      total: '',
    }

    $http.post(`${SERVER_CONTEXT}/api/checkRecord/app/queryDailyCheckByCondition`,
      angular.extend(this.queryData, this.paginationData1)
        )
      .then((resp) => {
        this.dailyCheckList = resp.data.data;
        this.paginationData.total = resp.data.total;
    });
  };

  // 分页查询方法
  this.paginationQuery = () => {
    if (this.paginationData.pageNum) {
      this.paginationData2 = {
        pageNum: this.paginationData.pageNum-1,
        pageSize: 5,
        total: '',
      }
    } else {
      this.paginationData2 = {
        pageNum: 0,
        pageSize: 5,
        total: '',
      }
    }
    this.showDetailList = false;
    $http.post(`${SERVER_CONTEXT}/api/checkRecord/app/queryDailyCheckByCondition`,
      angular.extend(this.queryData, this.paginationData2)
        )
      .then((resp) => {
        this.dailyCheckList = resp.data.data;
        this.paginationData.total = resp.data.total;
    });

  };

  // 查询
  this.query = (param) => {
    // 问题处理状态
    if (this.problemStatus == 3) {
      this.queryData.taskStatusList=[];
      this.queryData.taskStatusList.push(3);
    } else if (this.problemStatus == 1) {
      this.queryData.taskStatusList=[];
      this.queryData.taskStatusList.push(0,1,2);
    } else {
      this.queryData.taskStatusList=[];
    }
    // 巡查开始时间大小判断
    if(param.endTime.$viewValue && param.startTime.$viewValue){
      if (param.startTime.$viewValue < param.endTime.$viewValue) {
        this.paginationQuery();
    } else {
        layer.alert('巡查开始时间应小于结束时间');
      }
    } else {
      this.paginationQuery();
    }

  }

  // 重置
  this.reset = () => {
    this.queryData = {
      queryType: 0,
      bidId : $rootScope.activeBid.tenderId,
    };
  }

  // 显示巡查内容
  this.showDetail = (id) => {
    this.showDetailList = true;
    $http
      .get(`${SERVER_CONTEXT}/api/checkRecord/app/queryContentList/${id}`,{})
      .then((resp) => {
        this.dailyCheckDetailList = resp.data;
        document.getElementById('check_list').scrollIntoView();
    });
  }

  // 查看巡查轨迹
  this.showTrackHistory = (id) => {
    $scope.id = id;

    $http
      .post(`${SERVER_CONTEXT}/api/securityActivities/patrolTrack/queryPatrolTrack`,{taskId: id})
      .success((data) => {
        if ($scope.id == 95) {
          ngDialog.open({
            template: 'patrolPath',
            className: 'ngdialog-theme-default pa-special-check-item-list-theme patrol-path rectification ',
            scope: $scope,
            controllerAs: 'vm',
            controller: function specialDetailCtrl($rootScope, $scope, $http, ngDialogProblem) {
              'ngInject';
              console.log($scope.id);
              $http
                .get(`${SERVER_CONTEXT}/api/checkRecord/app/queryContentList/${id}`,{})
                .then((resp) => {
                  this.dailyCheckDetailList = resp.data;
                  this.initMap();
              });

              // 默认展示地图
              this.shouldMapShow = true;

              // 展示问题记录
              this.showProblemDetail = (id, index) => {
                this.shouldMapShow = false;
                this.selectedIndex = index;
                let _this = this;
                this.isUploading = false;

                this.reasons = [{
                  id: 1,
                  name: '管理制度',
                  active: false
                }, {
                  id: 2,
                  name: '岗位职责',
                  active: false
                }, {
                  id: 3,
                  name: '专项方案',
                  active: false
                }, {
                  id: 3,
                  name: '安全措施',
                  active: false
                }, {
                  id: 4,
                  name: '思想行为',
                  active: false
                }, {
                  id: 5,
                  name: '经费保障',
                  active: false
                }, {
                  id: 6,
                  name: '其他',
                  active: false
                }];

                this.rectificationList = {};
                this.detailList = {
                  problemModifyBean: {
                    fileBeanList: [],
                  },
                };
                // 获取专项检查详情-问题记录
                this.getSpecialDetail = () => {
                  $http.get(`${SERVER_CONTEXT}/api/checkRecord/app/queryContentDetail/${id}`)
                    .then((resp) => {
                      this.detailList = resp.data;
                      this.rectificationList = this.detailList.problemModifyBean ? this.detailList.problemModifyBean : {};
                      this.approval = this.detailList.problemModifyBean ? this.detailList.problemModifyBean : {};
                      handleProblemReasons2ViewModel(resp.data);

                      function handleProblemReasons2ViewModel(respData) {
                        if (respData && respData.problemModifyBean && respData.problemModifyBean.causeAnalysis) {
                          let activeReasons = respData.problemModifyBean.causeAnalysis.split(',');
                          activeReasons.forEach((activeReason) => {
                            _this.reasons.forEach((reason) => {
                              if (reason.name == activeReason) {
                                reason.active = true;
                              }
                            })
                          });
                        }
                      }
                    });
                }

                // 上传新增整改后照片
                this.submit = () => {
                  var causeAnalysis = "";
                  // 上传图片
                  let fileBeanList = (this.detailList.problemModifyBean && this.detailList.problemModifyBean.fileBeanList) || [];
                  // modifyImage 属性用于接收附件token 多个附件以逗号分隔

                  this.rectificationList.problemImageIds = fileBeanList.map(item => item.id).join(',');
                  this.rectificationList.problemId = id;

                  // 原因分析
                  this.reasons.forEach(function(item, index) {
                    if (item.active) {
                      causeAnalysis = causeAnalysis ? causeAnalysis + ',' + item.name : item.name;
                    }
                  });

                  this.rectificationList.causeAnalysis = causeAnalysis;

                  $http.post(`${SERVER_CONTEXT}/api/checkRecord/app/addProblemModify`,
                      this.rectificationList
                    )
                    .then((resp) => {
                      if (resp.data.success) {
                        layer.msg(resp.data.message);
                        this.getSpecialDetail();
                        deferred.resolve(resp);
                      } else {
                        layer.alert(resp.data.message);
                        deferred.reject(resp);
                      }
                    });
                }

                // 展示审批
                this.isAuditable = function() {
                  if (this.detailList.problemFoundUserId == $rootScope.userInfo.userId && this.detailList.problemStatus == 1) {
                    return true;
                  }
                  return false;
                }

                // 提交审批意见
                this.approvalSubmit = () => {
                  let reqData = {
                    checkResult: parseInt(this.approval.checkResult),
                    problemId: id,
                    comments: this.approval.comments
                  }

                  $http.post(`${SERVER_CONTEXT}/api/checkRecord/app/auditModifyProblem`,
                      reqData
                    )
                    .then((resp) => {
                      if (resp.data.success) {
                        layer.msg(resp.data.message);
                        // $state.reload();
                        this.getSpecialDetail();
                        deferred.resolve(resp);
                      } else {
                        layer.alert(resp.data.message);
                        deferred.reject(resp);
                      }
                    });
                }

                // 文件预览
                this.preview = (archiveDetail) => {
                  let url = $state.href('documentPreview', {
                    id: archiveDetail.id,
                  });
                  window.open(url,'_blank');
                }

                // 重置审批意见
                this.reset = () => {
                  this.approval = {};
                }

                this.initPage = () => {
                  // 获取问题详情
                  this.getSpecialDetail();
                }

                // 初始化页面
                this.initPage();
              }

              // 展示地图
              this.showMap = () => {
                this.shouldMapShow = true;
              }



              /*
               * immediate execution will throw error, this function should run after link function
               * running in ajax callback function is seen as a tricky way solving executive order problem
               */
              this.initMap = () => {
                let imageUrlStart = require(`../../../assets/images/position-start.png`);
                let imageUrlIng = require(`../../../assets/images/position-ing.png`);
                let imageUrlEnd = require(`../../../assets/images/position-end.png`);

                let map = window.map = new BMap.Map("bdmap_container");
                map.enableScrollWheelZoom();

                let lushu;
                // 实例化一个驾车导航用来生成路线
                let drv = new BMap.DrivingRoute('镇江', {
                  onSearchComplete: function(res) {
                    if (drv.getStatus() == BMAP_STATUS_SUCCESS) {
                        let plan = res.getPlan(0);
                        let arrPois =[];
                        for(let j=0;j<plan.getNumRoutes();j++){
                            let route = plan.getRoute(j);
                            arrPois= arrPois.concat(route.getPath());
                        }
                        map.addOverlay(new BMap.Polyline(arrPois, {strokeColor: '#111'}));
                        console.log(JSON.stringify(arrPois));
                        map.setViewport(arrPois);

                        let positionPoint = {
                          startPoi: {
                            lat: arrPois[0].lat,
                            lng: arrPois[0].lng,
                          },
                          endPoi: {
                            lat: arrPois[arrPois.length - 1].lat,
                            lng: arrPois[arrPois.length - 1].lng,
                          },
                          problemPois:[
                            {
                              lat: arrPois[parseInt(arrPois.length/2)].lat,
                              lng: arrPois[parseInt(arrPois.length/2)].lng,
                            },
                          ]
                        };

                        let pointTime = {
                          startTime: '2016-9-13 13:56',
                          inTime: '2016-9-13 14:56',
                          endTime: '2016-9-13 15:56',
                        }

                        let startPoi = new BMap.Point(positionPoint.startPoi.lng, positionPoint.startPoi.lat),
                            endPoi   = new BMap.Point(positionPoint.endPoi.lng, positionPoint.endPoi.lat),
                            problemPois = [];
                        positionPoint.problemPois.forEach((poi) => {
                          problemPois.push(new BMap.Point(poi.lng, poi.lat));
                        });

                        let markerStart = new BMap.Marker(startPoi, {icon:new BMap.Icon(imageUrlStart, new BMap.Size(36, 36))});
                        let markerEnd = new BMap.Marker(endPoi, {icon:new BMap.Icon(imageUrlEnd, new BMap.Size(36, 36))});
                        let markerProblems = [];

                        let problemIcon = new BMap.Icon(imageUrlIng, new BMap.Size(36, 36));
                        problemPois.forEach((point) => {
                          let problemMakerItem = new BMap.Marker(point, {icon: problemIcon});
                          markerProblems.push(problemMakerItem);
                        });

                        map.addOverlay(markerStart);
                        map.addOverlay(markerEnd);
                        markerProblems.forEach((marker) => {
                          map.addOverlay(marker);
                        });

                        // 图标点击事件-开始位置
                        let optsStart = {
                          width: 0, // 信息窗口宽度
                          height: 50, // 信息窗口高度
                          title: "<h3>开始位置</h3>", // 信息窗口标题
                        }

                        // 图标点击事件-结束位置
                        let optsEnd = {
                          width: 0, // 信息窗口宽度
                          height: 50, // 信息窗口高度
                          title: "<h3>结束位置</h3>", // 信息窗口标题
                        }

                        // 图标点击事件-内容
                        let optsProblem = {
                          width: 0, // 信息窗口宽度
                          height: 50, // 信息窗口高度
                          title: "<h3>内容 01</h3>", // 信息窗口标题
                        }

                        let infoWindowStart = new BMap.InfoWindow(pointTime.startTime, optsStart),
                            infoWindowEnd = new BMap.InfoWindow(pointTime.endTime, optsEnd),
                            infoWindowProblem = new BMap.InfoWindow(pointTime.inTime, optsProblem); // 创建信息窗口对象
                        markerStart.addEventListener("click", function() {
                          map.openInfoWindow(infoWindowStart, startPoi); //开启信息窗口
                        });
                        markerEnd.addEventListener("click", function() {
                          map.openInfoWindow(infoWindowEnd, endPoi); //开启信息窗口
                        });
                        markerProblems.forEach((marker) => {
                          marker.addEventListener("click", function() {
                            problemPois.forEach((point) => {
                              map.openInfoWindow(infoWindowProblem, point); //开启信息窗口
                            });
                          });
                        });
                    }
                  }

                });
                drv.search('京口区政府', '江苏大学梦溪校区');
              }

            }
          });
        } else if (!data.data.trackHistoryPoints || !data.data.trackHistoryPoints.length) {
          data.hasTrackPois = false;
          layer.alert('该次巡查任务没有轨迹');
        } else {
          data.hasTrackPois = true;
        }
      })
      .then((data) => {
        if (!data.data.hasTrackPois) {
          return false;
        }

        $scope.trackData = data.data.data;
        ngDialog.open({
          template: 'patrolPath',
          className: 'ngdialog-theme-default pa-special-check-item-list-theme patrol-path rectification ',
          scope: $scope,
          controllerAs: 'vm',
          controller: specialDetailCtrl,
        });

      });

  }

  // 查看内容详情
  this.checkDetail = (item) => {
    ngDialogProblem
      .confirm(item.problemId)
      .then((data) => {
        this.paginationQuery();
        this.showDetail(item.taskId);
      });
  }

  // 升序、降序（参数没定）
  this.up = (param,index) => {
    this.queryData.columeName = param;
    this.queryData.order = index;
    this.paginationQuery();
  }



  this.initPage = () => {
    // 获取巡查列表
    // this.paginationQuery();
  }

  // 初始化
  this.initPage();

}

export default dailyCheckCtrl;